package jdktcp.server;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JDKServer05ConnectionReset {

    static ExecutorService pool = Executors.newFixedThreadPool(100);

    public JDKServer05ConnectionReset() throws Exception {
        ServerSocket server = new ServerSocket(9999);
        System.out.println("init server :" + server);
        while (true) {
            Socket socket = server.accept();
            System.out.println("--->" + socket);
            execute(socket);
        }
    }

    private void execute(Socket socket) {
        Socket finalSocket = socket;
        pool.submit(() -> {
            try {
                byte[] buff = new byte[1024];
                InputStream in = finalSocket.getInputStream();
                in.read(buff);
                System.out.println("revice==>" + new String(buff).trim());
                TimeUnit.SECONDS.sleep(10);

                OutputStream out = finalSocket.getOutputStream();
                out.write("nihao client".getBytes());
                System.out.println("send resp finish <---");

                if (true) {
                    //服务端响应数据，写OutputStream后未进行close操作,直接关闭系统会造成客户端Connection reset
                    System.exit(0);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //服务端执行完毕后不关闭socket
                IOUtils.closeQuietly(finalSocket);
                System.out.println("socket close:" + finalSocket);
            }
        });
    }

    public static void main(String[] args) throws Exception {
        new JDKServer05ConnectionReset();
    }
}
